package com.douya.common.converter;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;


/**
 * Boolean类型转化器
 *
 * @Author 胡晨烨
 * @Date 2022/10/18
 */
@MappedTypes({Boolean.class}) //指定java中的类型
@MappedJdbcTypes({JdbcType.INTEGER}) //指定数据库中的数据类型
public class BooleanConverter<E> extends BaseTypeHandler<E> {


    public Integer convertToDatabaseColumn(Boolean attribute) {
        return attribute == null || !attribute ? 0 : 1;
    }


    public Boolean convertToEntityAttribute(Integer dbData) {
        return Objects.equals(1, dbData);
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, E e, JdbcType jdbcType) throws SQLException {
        Integer convert = convertToDatabaseColumn((Boolean) e);
        preparedStatement.setInt(i, convert);
    }

    @Override
    public E getNullableResult(ResultSet resultSet, String s) throws SQLException {
        Integer dbData = resultSet.getInt(s);
        return (E) convertToEntityAttribute(dbData);
    }

    @Override
    public E getNullableResult(ResultSet resultSet, int i) throws SQLException {
        Integer dbData = resultSet.getInt(i);
        return (E) convertToEntityAttribute(dbData);
    }

    @Override
    public E getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        Integer dbData = callableStatement.getInt(i);
        return (E) convertToEntityAttribute(dbData);
    }
}